import { Random, mock } from 'mockjs';
import { parse } from 'url';
// 职称
const academicTitles = {
  assistant: '助教',
  lecture: '讲师',
  adjunctProfessor: '副教授',
  professor: '教授',
};
// 学位
const academicDegrees = { doctor: '博士', postDoctor: '博士后' };
// 所属系
const departments = {
  ch: '测绘中心实验室',
  yg: '遥感科学与技术系',
  zh: '资源环境与城乡规划管理系',
  cx: '土地资源管理系',
  dx: '测量工程系',
  tg: '地理信息科学系',
};
// 职位
const divisions = [
  '党政办公室',
  '团委副书记',
  '学生工作办公室',
  '教学与科研工作办公室',
  '研究生工作办公室',
  '学院学位委员会',
  '学院学术委员会',
];
// 政治面貌
const politicalOutlooks = [
  '中共党员',
  '中共预备党员',
  '民革党员',
  '民盟盟员',
  '民建会员',
  '民进会员',
  '农工党党员',
  '致公党党员',
  '九三学社社员',
  '台盟盟员',
  '无党派人士',
];

// 所属科研平台
const researchPlatforms = [
  '国家测绘地理信息局矿山空间信息技术实验室',
  '河南省测绘地理信息局矿山空间技术实验室',
  '测绘科学与技术博士后科研流动站',
  '河南省空间信息获取处理院士工作站',
  '国土部野外科学观测研究基地',
  '开采沉陷与土地规划利用研究所',
  '智慧中原地理信息河南省协同创新分中心',
  '北斗导航技术河南省协同创新分中心',
  '土地经济与城乡发展中心',
];

const memos = [
  '-',
  Random.csentence(3, 5),
  Random.csentence(3, 5),
  Random.csentence(3, 5),
  Random.csentence(3, 5),
  Random.csentence(3, 5),
];

const papersLogo = [
  'http://qiniu.fengweio.com/1556700090566',
  'http://qiniu.fengweio.com/1556700090706',
  'http://qiniu.fengweio.com/1556700090736',
  'http://qiniu.fengweio.com/1556700090763',
  'http://qiniu.fengweio.com/1556700090792',
  'http://qiniu.fengweio.com/1556700090831',
  'http://qiniu.fengweio.com/1556700090866',
  'http://qiniu.fengweio.com/1556700090902',
  'http://qiniu.fengweio.com/1556700090933',
  'http://qiniu.fengweio.com/1556700127274',
  'http://qiniu.fengweio.com/1556700127292',
  'http://qiniu.fengweio.com/1556700127316',
  'http://qiniu.fengweio.com/1556700127348',
  'http://qiniu.fengweio.com/1556700127372',
  'http://qiniu.fengweio.com/1556700127399',
  'http://qiniu.fengweio.com/1556700127434',
  'http://qiniu.fengweio.com/1556700127464',
  'http://qiniu.fengweio.com/1556700127493',
  'http://qiniu.fengweio.com/1556700162581',
  'http://qiniu.fengweio.com/1556700162592',
  'http://qiniu.fengweio.com/1556700162607',
  'http://qiniu.fengweio.com/1556700162626',
  'http://qiniu.fengweio.com/1556700162642',
  'http://qiniu.fengweio.com/1556700162667',
  'http://qiniu.fengweio.com/1556700162697',
  'http://qiniu.fengweio.com/1556700162720',
  'http://qiniu.fengweio.com/1556700162747',
  'http://qiniu.fengweio.com/1556700186434',
  'http://qiniu.fengweio.com/1556700186458',
  'http://qiniu.fengweio.com/1556700186474',
  'http://qiniu.fengweio.com/1556700186494',
  'http://qiniu.fengweio.com/1556700186519',
  'http://qiniu.fengweio.com/1556700186539',
  'http://qiniu.fengweio.com/1556700186570',
  'http://qiniu.fengweio.com/1556700186599',
  'http://qiniu.fengweio.com/1556700186631',
  'http://qiniu.fengweio.com/1556700194423',
];

let teacherList = [];
// mock 教师列表
for (let i = 0; i < 46; i += 1) {
  const tec = {
    id: mock('@id'), // 用户ID
    key: mock('@id'),
    name: mock('@cname'), // 姓名
    department: Object.keys(departments)[i % 6], // 所属系
    academicTitle: Object.keys(academicTitles)[i % 4],
    academicDegree: Object.keys(academicDegrees)[i % 2],
    description: mock('@cparagraph()'), // 个人简介
    status: Math.floor(Math.random() * 10) % 3,
    todoListCount: 3, // 待办事项
    updatedAt: new Date(new Date().getTime() - 1000 * 60 * 60 * 2 * i),
    createdAt: Random.datetime(),
  };
  tec.avatar = Random.image('100x100', '#228cee', '#FFFFFF', tec.name.substr(0, 1));

  teacherList.push(tec);
}

// Mock 操作日志列表
function mockOperations(name) {
  const res = {};

  for (let index = 0; index < 3; index += 1) {
    const eachCount = Random.integer(3, 10);
    const eachResult = [];

    for (let i = 0; i < eachCount; i += 1) {
      const obj = {
        key: Random.guid(),
        type: Random.ctitle(3, 5),
        name,
        status: ['agree', 'disagree'][Random.integer(0, 1)],
        updatedAt: Random.datetime(),
        memo: memos[Random.integer(0, 5)],
      };

      eachResult.push(obj);
    }
    res[`tab${index + 1}`] = eachResult;
  }

  return res;
}

// Mock 论文列表
function mockPapers() {
  const count = Random.integer(10, 20);
  const res = [];

  for (let index = 0; index < count; index += 1) {
    res.push({
      avatar: Random.image('50x50', '#228cee', '#FFFFFF', Random.cword()),
      title: Random.ctitle(5, 10),
      description: Random.cparagraph(2),
      content: Random.cparagraph(),
      logo: papersLogo[Random.integer(0, 36)],
    });
  }

  return res;
}

function getFakeTeacherList(req, res, u) {
  let url = u;
  if (!url || Object.prototype.toString.call(url) !== '[object String]') {
    // eslint-disable-next-line prefer-destructuring
    url = req.url;
  }

  const params = parse(url, true).query;

  let dataSource = teacherList;

  if (params.sorter) {
    const s = params.sorter.split('_');
    dataSource = dataSource.sort((prev, next) => {
      if (s[1] === 'descend') {
        return next[s[0]] - prev[s[0]];
      }

      return prev[s[0]] - next[s[0]];
    });
  }

  if (params.status) {
    const status = params.status.split(',');
    let filterDataSource = [];

    status.forEach(s => {
      filterDataSource = filterDataSource.concat(
        dataSource.filter(data => parseInt(data.status, 10) === parseInt(s[0], 10))
      );
    });

    dataSource = filterDataSource;
  }

  if (params.name) {
    dataSource = dataSource.filter(data => data.name.indexOf(params.name) > -1);
  }

  if (params.department) {
    dataSource = dataSource.filter(data => data.department === params.department);
  }

  if (params.academicTitle) {
    dataSource = dataSource.filter(data => data.academicTitle === params.academicTitle);
  }

  if (params.academicDegree) {
    dataSource = dataSource.filter(data => data.academicDegree === params.academicDegree);
  }

  let pageSize = 10;
  if (params.pageSize) {
    pageSize = params.pageSize * 1;
  }

  const result = {
    list: dataSource,
    pagination: {
      total: dataSource.length,
      pageSize,
      current: parseInt(params.currentPage, 10) || 1,
    },
  };

  return res.json(result);
}

function postFakeTeacherList(req, res, u, b) {
  let url = u;
  if (!url || Object.prototype.toString.call(url) !== '[object String]') {
    url = req.url; // eslint-disable-line
  }
  const body = (b && b.body) || (req.body.body ? req.body.body : req.body);

  const {
    name = '佚名',
    description = '请添加简介',
    department = 'ch',
    id,
    academicTitle = 'assistant',
    academicDegree = 'doctor',
    status = 0,
    createdAt,
    key = [],
  } = body;

  const method = body.method ? body.method : req.body.method;

  switch (method) {
    case 'delete':
      teacherList = teacherList.filter(item => key.every(k => k !== item.key));
      break;
    case 'update':
      teacherList = teacherList.map(item => {
        if (item.id === id) {
          Object.assign(item, {
            name,
            description,
            department,
            academicTitle,
            academicDegree,
            status,
            createdAt,
            updatedAt: new Date().getTime(),
          });
        }
        return item;
      });
      break;
    case 'post':
      teacherList.unshift({
        name,
        description,
        department,
        academicTitle,
        academicDegree,
        id: mock('@id'),
        key: mock('@id'),
        createdAt: new Date().getTime(),
        updatedAt: new Date().getTime(),
        avatar: Random.image('100x100', '#228cee', '#FFFFFF', name.substr(0, 1)),
        status: 2,
      });
      break;
    default:
      break;
  }

  return getFakeTeacherList(req, res, u);
}

function getFakeTeacherDetail(req, res) {
  const { id } = req.query;
  const teacherInfo = teacherList.filter(item => item.id === id);

  const name = teacherInfo[0].name || '佚名';

  // TODO: 加点东西吧
  const userInfo = {
    ...teacherInfo[0],
    sex: Random.boolean() ? '男' : '女', // 性别
    birthDate: Random.date('yyyy-MM-dd'), // 出生年月
    married: Random.boolean(), // 婚否
    nativePlace: Random.county(true), // 籍贯
    politicalOutlook: politicalOutlooks[Random.integer(0, 10)], // 政治面貌
    contactNumber: `1${[3, 5, 7, 8][Random.integer(0, 3)]}${Random.integer(100000000, 999999990)}`, // 联系电话
    email: Random.email('hpu.edu.cn'), // 邮箱
    post: divisions[Random.integer(0, 8)], // 职位
    researchPlatform: researchPlatforms[Random.integer(0, 8)], // 科研平台
    postalAddress: Random.county(true), // 通讯地址
    undergraduateCollege: '清华大学', // 本科毕业院校
    masterCollege: '北京大学', // 研究生毕业院校
    doctoralCollege: '耶鲁大学', // 博士毕业院校
    papers: mockPapers(), // 主要论文
    researchDirection: '遥感解译、测绘平差理论、土壤侵蚀', // 研究方向
    operations: mockOperations(name),
  };

  res.json(userInfo);
}

/**
 * - [x] 获取教师信息
 * - [x] 增加、更新、删除教师
 */

export default {
  'GET /api/teachers/detail': getFakeTeacherDetail, // 获取教室详情
  'GET /api/teachers': getFakeTeacherList, // 获取 teacherList
  'POST /api/teachers': postFakeTeacherList, // 增加、更新、删除教师 ==> 返回为新的 teacherList
};
